package com.zb.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.zb.common.exception.BusinessException;
import com.zb.common.mapper.MenuMapper;
import com.zb.common.po.enums.MenuType;
import com.zb.common.po.model.Menu;
import com.zb.common.po.query.MenuQuery;
import com.zb.service.MenuService;

@Service(value = "menuService")
public class MenuServiceImpl implements MenuService {

    @Resource
    private MenuMapper menuMapper;

    @Override
    public List<Menu> findAllMenu() {
        List<Menu> list = this.menuMapper.selectList(null);
        return list;
    }

    @Override
    public List<Menu> findAllMenuByRoles(List<String> roleIds) {
        List<Menu> list = menuMapper.selectMenuByRoleIds(roleIds);
        return list;
    }

    @Override
    public void saveMenu(Menu menu) throws BusinessException {
        if (null == menu.getId()) {
            if (null == menu.getMenuType()) {
                menu.setMenuType(MenuType.MENU);
            }
            menuMapper.insertMenu(menu);
        } else {
            menuMapper.updateMenu(menu);
        }
    }

    @Override
    public void deleteMenu(Integer id) throws BusinessException {
        List<Menu> list = this.menuMapper.selectList(null);
        List<Integer> childIds = new ArrayList<Integer>();
        getAllChildIds(list, id, childIds);
        menuMapper.deleteMenu(childIds);
    }

    private List<Integer> getAllChildIds(List<Menu> list, int pid,
            List<Integer> childIds) {
        childIds.add(pid);
        Iterator<Menu> iterator = list.iterator();
        while (iterator.hasNext()) {
            Menu subMenu = iterator.next();
            if (pid == subMenu.getpId().intValue()) {
                getAllChildIds(list, subMenu.getId(), childIds);
            }
        }
        return childIds;
    }

    @Override
    public Menu findPmenuByUrl(String url) {
        /*
         * 查询当前url的父菜单，如果url不唯一，那么直接返回一个空对象，url不唯一的时候，那么父菜单也不唯一，那么就不知道左侧菜单要选中哪一个，
         * 直接返回空对象，不做左侧菜单选中操作。 这里只做菜单按钮的选中操作，也就是进入内页的时候，让左侧菜单选中
         */
        MenuQuery query = new MenuQuery();
        query.setMenuUrl(url);
        query.setMenuType(MenuType.BUTTON);
        List<Menu> list = this.menuMapper.selectList(query);
        if (list.size() == 1) {
            Menu meue = list.get(0);
            query = new MenuQuery();
            query.setMenuId(meue.getpId());
            list = this.menuMapper.selectList(query);
            return list.get(0);
        }
        return new Menu();
    }
}
